<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="出单日期">
              <a-range-picker v-model="timeData" @change="timeChange" format="YYYY-MM-DD HH:mm:ss" :show-time="true" style="width: 100%;" />
            </a-form-item>
          </a-col> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="产品类目" :labelCol="{xs: { span: 24 },sm: { span: 7 },}" :wrapperCol="{xs: { span: 24 },sm: { span: 16 },}">
              <a-tree-select
                allow-clear
                v-model="queryParam.categoryId"
                :replaceFields="replaceFields"
                :filterTreeNode="filterTreeNode"
                show-search
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择产品类目"
                tree-default-expand-all
                :getPopupContainer="node => node.parentNode"
              >
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="SKU">
              <a-input placeholder="请输入SKU" v-model.trim="queryParam.sku"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="中文名称">
              <a-input placeholder="请输入中文名称" v-model.trim="queryParam.productName"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="英文名称">
                <a-input placeholder="请输入英文名称" v-model.trim="queryParam.productTitle"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" v-has="'ProductLibraryBillList:createBy'">
              <a-form-item label="产品专员">
                <j-search-select-user v-model="queryParam.createBy" placeholder="请输入并选择产品专员"></j-search-select-user>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" v-has="'ProductLibraryBillList:sysOrgCode'">
              <a-form-item label="专员部门">
                <j-select-depart v-model="queryParam.sysOrgCode" :trigger-change="true" customReturnField="orgCode"></j-select-depart>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button> -->
      <a-button type="primary" icon="download" @click="handleExportXls('产品库-标签')">导出</a-button>
      <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload> -->
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query> -->
      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown> -->
      <div style="float: right;">
        <span style="margin-right: 10px;color: #cecece;font-size: 12px;">更新时间：{{ statisticsDate.statisticsTime }}</span>
        <span style="margin-right: 10px; font-size: 16px;">共计：{{ statisticsDate.total }}</span>
        <j-dict-select-tag v-model="queryParam.stsType" type="radioButton" :options="dictOptions" @change="handleChange" />
      </div>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        :key="keyNumber"
        id="custom-table"
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :customRow="selectRowData">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="pictureUrlSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="width: 80px;height: 80px;object-fit: cover;cursor: pointer;border-radius: 4px;" @click="handleImg(getImgView(text))"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>
        <template slot="nameSlot" slot-scope="text, record">
          <div style="text-align: left; width: 400px; white-space: wrap;">
            <p style="font-weight: 700;">{{ record.sku }}</p>
            <p>英文名称：{{ record.productTitle }}</p>
            <p>中文名称：{{ record.productName }}</p>
            <p>产品类目：{{ record.categoryId_dictText }}</p>
          </div>
        </template>
        <template slot="yesterdayNum" slot-scope="text, record">
          <button class="custom-button" @click="handleNumber(record, 'yesterday')">{{ text }}</button>
        </template>
        <template slot="oneWeekNum" slot-scope="text, record">
          <button class="custom-button" @click="handleNumber(record, 'week')">{{ text }}</button>
        </template>
        <template slot="oneMonthNum" slot-scope="text, record">
          <button class="custom-button" @click="handleNumber(record, 'month')">{{ text }}</button>
        </template>
        <template slot="halfYearNum" slot-scope="text, record">
          <button class="custom-button" @click="handleNumber(record, 'halfYear')">{{ text }}</button>
        </template>
        <template slot="oneYearNum" slot-scope="text, record">
          <button class="custom-button" @click="handleNumber(record, 'year')">{{ text }}</button>
        </template>
        <template slot="totalNum" slot-scope="text, record">
          <button class="custom-button" @click="handleNumber(record, '')">{{ text }}</button>
        </template>

        <!-- <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span> -->

      </a-table>
    </div>

    <product-library-bill-modal ref="modalForm" @ok="modalFormOk"></product-library-bill-modal>
  </a-card>
</template>

<script>
  import { getAction } from '@api/manage'
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ProductLibraryBillModal from './modules/ProductLibraryBillModal'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import { productMixins } from '@/views/productLibrary/mixins/productMixins'
  import { colAuthFilter } from "@/utils/authFilter"
  export default {
    name: 'ProductLibraryBillList',
    mixins:[JeecgListMixin, mixinDevice, productMixins],
    components: {
      ProductLibraryBillModal
    },
    data () {
      return {
        description: '产品库-标签管理页面',
        timeData: [],
        statisticsDate: {},
        queryParam: {
          stsType: 'sku'
        },
        ipagination:{
          current: 1,
          pageSize: 50,
          pageSizeOptions: ['50', '100', '150','200','500','1000'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'产品图片',
            align:"center",
            dataIndex: 'pictureUrl',
            scopedSlots: { customRender: 'pictureUrlSlot' }
          },
          {
            title:'产品信息',
            align:"center",
            dataIndex: 'name',
            scopedSlots: { customRender: 'nameSlot' }
          },
          {
            title:'产品专员',
            align:"center",
            dataIndex: 'createBy'
          },
          {
            title:'昨日销量',
            align:"center",
            dataIndex: 'yesterdayNum',
            scopedSlots: { customRender: 'yesterdayNum' }
          },
          {
            title:'一周内销量',
            align:"center",
            dataIndex: 'oneWeekNum',
            scopedSlots: { customRender: 'oneWeekNum' }
          },
          {
            title:'一月内销量',
            align:"center",
            dataIndex: 'oneMonthNum',
            scopedSlots: { customRender: 'oneMonthNum' }
          },
          {
            title:'半年内销量',
            align:"center",
            dataIndex: 'halfYearNum',
            scopedSlots: { customRender: 'halfYearNum' }
          },
          {
            title:'一年内销量',
            align:"center",
            dataIndex: 'oneYearNum',
            scopedSlots: { customRender: 'oneYearNum' }
          },
          {
            title:'历史销量（总）',
            align:"center",
            dataIndex: 'totalNum',
            scopedSlots: { customRender: 'totalNum' }
          }
        ],
        url: {
          list: "/hzkj-oms/oms/product/statistics/list",
          delete: "/hzkj-oms/oms/product/statistics/delete",
          deleteBatch: "/hzkj-oms/oms/product/statistics/deleteBatch",
          exportXlsUrl: "/hzkj-oms/oms/product/statistics/exportXls",
          importExcelUrl: "hzkj-oms/oms/product/statistics/importExcel",
          statisticsDate: "/hzkj-oms/oms/product/statistics/statisticsDate"
        },
        dictOptions: [
          {
            text: 'SKU',
            value: 'sku'
          },
          {
            text: 'SPU',
            value: 'spu'
          }
        ],
        superFieldList:[],
        keyNumber: 0
      }
    },
    created() {
      this.disableMixinCreated=true;
      this.columns = colAuthFilter(this.columns,'ProductLibraryBillList:');
      this.initDictConfig();
      this.getSuperFieldList();
      this.loadData_('', 'queryMyCategory');
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    watch: {
      dataSource: {
        handler(val){
          //清除合计
          this.keyNumber++;
          if(val && val.length){
            this.handleStatistics();
          }
          this.getStatisticsDate();
        }
      }
    },
    methods: {
      initDictConfig(){
      },
      selectRowData(record,index){
        const that = this
        return {
          on:{
            dblclick:() => {
              // this.handleDetail(record)
            }
          }
        }
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'name',text:'标签名称',dictCode:''})
        fieldList.push({type:'int',value:'type',text:'标签类型',dictCode:'product_tag_type'})
        fieldList.push({type:'string',value:'createBy',text:'创建人',dictCode:''})
        this.superFieldList = fieldList
      },
      timeChange(time1, time2){
        this.queryParam.startTime = time2 && time2[0];
        this.queryParam.endTime = time2 && time2[1];
      },
      handleImg(src){
        if(src){
          this.$viewerApi({images: [src]});
        }
      },
      handleStatistics(){
        //处理合计
        this.$nextTick(() => {
          let yesterdayNum = this.dataSource.reduce((prev, cur) => {
            return prev + +cur.yesterdayNum;
          }, 0)
          let oneWeekNum = this.dataSource.reduce((prev, cur) => {
            return prev + +cur.oneWeekNum;
          }, 0)
          let oneMonthNum = this.dataSource.reduce((prev, cur) => {
            return prev + +cur.oneMonthNum;
          }, 0)
          let halfYearNum = this.dataSource.reduce((prev, cur) => {
            return prev + +cur.halfYearNum;
          }, 0)
          let oneYearNum = this.dataSource.reduce((prev, cur) => {
            return prev + +cur.oneYearNum;
          }, 0)
          let totalNum = this.dataSource.reduce((prev, cur) => {
            return prev + +cur.totalNum;
          }, 0)
          let dom = document.getElementById('custom-table');
          let tbody = dom.querySelector('.ant-table-tbody');
          let tr = tbody.querySelectorAll('.ant-table-row')[0];
          let clonedNode = tr.cloneNode(true);
          clonedNode.querySelector('.ant-table-selection-column').innerHTML = '合计';
          clonedNode.querySelector('.ant-table-row-cell-break-word').innerHTML = '';
          // 兼容产品专员列数据权限
          clonedNode.querySelectorAll('td')[2].innerHTML = '';
          clonedNode.querySelectorAll('td')[3].innerHTML = '';
          let index = 4;
          if(this.columns.length === 10){
            clonedNode.querySelectorAll('td')[4].innerHTML = '';
          }else{
            index = 3;
          }
          clonedNode.querySelectorAll('td')[index + 1].innerHTML = yesterdayNum;
          clonedNode.querySelectorAll('td')[index + 2].innerHTML = oneWeekNum;
          clonedNode.querySelectorAll('td')[index + 3].innerHTML = oneMonthNum;
          clonedNode.querySelectorAll('td')[index + 4].innerHTML = halfYearNum;
          clonedNode.querySelectorAll('td')[index + 5].innerHTML = oneYearNum;
          clonedNode.querySelectorAll('td')[index + 6].innerHTML = totalNum;
          tbody.appendChild(clonedNode);
        })
      },
      handleChange(){
        //清除合计
        this.keyNumber++;
        this.loadData();
      },
      handleNumber(record, queryDimension){
        this.$refs.modalForm.edit(Object.assign({ queryDimension }, record));
        this.$refs.modalForm.title = "订单列表";
        this.$refs.modalForm.disableSubmit = true;
      },
      searchReset(){
        this.timeData = [];
        this.queryParam = {
          stsType: 'sku'
        }
        this.loadData(1);
      },
      getStatisticsDate(){
        let params = {
          ...this.queryParam,
          stsType: this.queryParam.stsType
        }
        getAction(this.url.statisticsDate, params).then((res) => {
          if(res.success){
            this.statisticsDate = res.result || {};
          }else{
            this.$message.warning(res.message);
          }
        })
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  .custom-button{
    color: #1890FF;
    cursor: pointer;
    background-color: transparent;
    border: none;
  }
</style>